<?php

namespace app\admin\controller\device;

use app\admin\model\DeviceModel;
use app\admin\model\DeviceTrendsModel;
use app\admin\model\ImeiModel;
use app\admin\model\UserModel;
use app\common\controller\Backend;
use app\common\Helper\AppTools;
use app\user\model\Devicetrends;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Request;

class Index extends Backend
{
    // 设备列表
    public function deviceList(Request $request)
    {
        $param = $request->param();
        $data = json_decode($param['data'], true);
        $deviceModel = new DeviceModel();
        $deviceTrendsModel = new DeviceTrendsModel();
        $searchImei = $data['imei'];
        $currpage = $data['page'];
        $pagesize = $data['size'];
        $where = [];
        if (!empty($searchImei)) $where[] = ['device_imei', 'like', "%{$searchImei}%"];
        $where[] = ['datastatus', '=', $deviceModel::NORMAL_DATASTATUS];
        $field = ['lc_user.mobile,lc_user.id,lc_user.openid,lc_device.id as device_id,lc_device.itime,lc_device.device_name,lc_device.device_bind_way,lc_device.device_imei,lc_device.version,lc_device.is_line,lc_device.device_bind_status,lc_device.device_bind_way,lc_device.cable,lc_device.temp,lc_device.device_status'];
        $listData = $deviceModel->table('lc_user,lc_device')
            ->where($where)
            ->field($field)
            ->where('lc_user.id=lc_device.user_id')
            ->select()->toArray();
        $deviceIds = array_column($listData, 'device_id');
        $moreAddress = $deviceTrendsModel->getAddressMore($deviceIds);
        $keyval = array_column($moreAddress, null, 'device_id');
        foreach ($listData as &$val) {
            if (empty($keyval[$val['device_id']]['address'])) {
                $val['address'] = '-等待设备上报-';
            } else {
                $val['address'] = $keyval[$val['device_id']]['address'];
            }
        }
        if (count($listData) < 1) return success([]);
        $count = $deviceModel->getCount($where);
        $list = AppTools::morePage($listData, $count, $currpage, $pagesize);
        return success($list);
    }

    // 设备状态开关
    public function switch(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $switch = $param['switch'];
        if (empty($id)) return fail([], 'id标识参数错误');
        if (empty($switch)) return fail([], 'switch标识参数错误');
        $deviceModel = new DeviceModel();
        $up = $deviceModel->getUpdate(['id' => $id], ['device_status' => $switch, 'utime' => time()]);
        if ($up) {
            upImei($id, 'is_stop', $switch);
            return success([]);
        }
        return fail([], '(UPDATE ERROR)更新错误');
    }

    // 删除设备
    public function delete(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        if (empty($id)) return fail([], 'id标识参数错误');
        $deviceModel = new DeviceModel();
        $imeiModel = new ImeiModel();
        $userModel = new UserModel();
        $deviceTrendsModel = new DeviceTrendsModel();
        $up = $deviceModel->getUpdate(['id' => $id], ['datastatus' => $deviceModel::DEL_DATASTATUS, 'utime' => time()]);
        if ($up) {
            $uid = $deviceModel->getUid($id);
            // 减少用户设备数量 
            $userModel->where(['id' => $uid])->setDec('device_num');
            // 释放imei
            upImei($id, 'status', $imeiModel::DEVICE_BIND_STATUS_NO);
            // 清除所有动态
            $deviceTrendsModel->where(['device_id' => $id])->update(['datastatus' => $deviceTrendsModel::DEL_DATASTATUS]);
            return success([]);
        }
        return fail([], '设备不存在或已被删除');
    }

    // 导入imei编码
    public function importExcel(Request $request)
    {
        try {
            $file = $_FILES['file'];
            if (empty($file) || !isset($file)) return fail([], 'file标识错误');
            $fileName = $file['name'];
            $size = $file['size'];
            $type = $file['type'];
            $tmp_name = $file['tmp_name'];
            if ($type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') return fail([], '只能上传xlsx文件');
            // if (!$size / 1024 / 1024 < 5) return fail([], '上传文件大小不能超过 5 MB');

            $imeiModel = new ImeiModel();

            $savePth = getcwd() . '/static/excel/import/'.strtotime(date("Y-m-d H:i:s")).'/';
            // 限制
            if (!file_exists($savePth . $fileName)) {
                mkdir($savePth, 0777, true);
                move_uploaded_file($tmp_name, $savePth . $fileName);
            }
            // 读取文件
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($savePth . $fileName);
            // 获取工作表数量
            $worksheetCount = $spreadsheet->getSheetCount();
            // 获取第一个工作表
            $worksheet = $spreadsheet->getActiveSheet();
            // 获取单元格的值
            $cellValue = $worksheet->getCell('A1')->getValue();
            // 遍历行数据
            $excel = [];
            foreach ($worksheet->getRowIterator() as $row) {
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                foreach ($cellIterator as $cell) {
                    // $cellValue = $cell->getValue();
                    // 处理单元格数据
                    if (!in_array($cell->getValue(), $excel)) {
                        $imei = [
                            'imei' => $cell->getValue(),
                            'itime' => time()
                        ];
                        array_push($excel, $imei);
                    }
                }
            }
            // 新增
            $insertData = $imeiModel->getInsertAll($excel);
            if ($insertData) {
                return success([]);
            } else {
                return fail([], '(INSERT ERRO)新增错误');
            }
        } catch (\Exception $e) {
            return fail([], '操作失败' . $e->getMessage() . $e->getLine());
        }
    }


    // 导出所有设备
    public function exportExcel(Request $request)
    {
        try {
            $deviceModel = new DeviceModel();
            $deviceTrendsModel = new DeviceTrendsModel();
            $field = ['id,device_name,itime,device_imei,version,network_card,device_bind_status'];
            $listData = $deviceModel->getSelect(['datastatus' => $deviceModel::NORMAL_DATASTATUS], $field);
            $device_ids = array_column($listData, 'id');
            $locate = $deviceTrendsModel->getSelect([['device_id', 'in', $device_ids], ['is_new', '=', $deviceTrendsModel::YES_NEW]], 'device_id,address');
            $keyval = array_column($locate, null, 'device_id');
            $trends = array_column($locate, 'device_id');
            foreach ($listData as $key => &$val) {
                $val['device_bind_status'] = $val['device_bind_status'] ? '已绑定' : '未绑定';
                if (in_array($val['id'], $trends)) {
                    $val['address'] = $keyval[$val['id']]['address'];
                } else {
                    $val['address'] = '-等待设备首次上报-';
                }
            }
            return success($listData);
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getLine();
        }
    }

    // 导出imei编码列表
    public function imeiList(Request $request)
    {
        $data = $request->param();
        $currpage = $data['page'];
        $pagesize = $data['size'];
        $imeiModel = new ImeiModel();
        $imeiList = $imeiModel->getSelect([], $currpage, $pagesize);
        return success($imeiList);
    }
    // 删除imei编码
    public function imeiDelete(Request $request)
    {
        $data = $request->param();
        $imeiModel = new ImeiModel();
        $imeiModel->imeiDelete(['imei' => $data['imei']]);
        return success("删除成功");
    }
}
